package com.fortune.service.impl;

import com.faneui.common.exception.BusinessException;
import com.faneui.common.utils.ListUtils;
import com.fortune.cache.Cache;
import com.fortune.common.Constants;
import com.fortune.dal.model.*;
import com.fortune.service.*;
import com.fortune.service.ananlysis.AnanlysisFactory;
import com.fortune.service.ananlysis.AnanlysisService;
import com.fortune.service.ananlysis.dto.BillMailInfoDTO;
import com.fortune.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
import java.util.List;
import java.util.Properties;

@Service
public class ScheduleServiceImpl implements ScheduleService {

    //创建日志实例化
    protected static final Logger logger = LoggerFactory.getLogger(ScheduleService.class);

    @Autowired
    private AnanlysisFactory ananlysisFactory;

    @Autowired
    private CustService custService;

    @Autowired
    private CardService cardService;

    @Autowired
    private CreditCardInfoService creditCardInfoService;

    @Autowired
    private CreditCardTypeService creditCardTypeService ;

    @Autowired
    private BillInfoService billInfoService ;

    @Override
    public void loadEmail(Integer custId, String email, String password) throws BusinessException {
        Properties p = new Properties();
        constructionQQMailProperties(p);
        try {
            Cust cust = custService.queryCust(custId);
            Session session = Session.getDefaultInstance(p, null);
            Store store = session.getStore("pop3");
            String host = "pop.qq.com";
            store.connect(host, email, password);
            Folder folder = store.getFolder("INBOX");//获取收件箱
            folder.open(Folder.READ_ONLY);//打开收件箱 只读   READ_WRITE--可读可写
            Message message[] = folder.getMessages();//得到收件箱中的所有邮件，并解析
            // 从后往前获取账单
            for (int i = message.length - 1; i >= 0; i--) {
                try {
                    //解析邮件
                    Message me = message[i];
                    AnanlysisService ananlysisService = ananlysisFactory.getAnanlysis(me);
                    Bank bank = ananlysisFactory.getBank(me);
                    if (ananlysisService != null) {
                        BillMailInfoDTO dto = ananlysisService.ananlysis(bank,me);
                        // 获取邮箱信息，存储到卡里

                        logger.info(dto.toString());
                        dto.setEmail(email);
                        dto.setPassword(password);
                        loadBillInfo(dto, cust);
                    }
                } catch (Exception ex) {
                    System.out.println(ex.getMessage());
                    ex.printStackTrace();
                }
            }
        } catch (Exception ex) {
            BusinessException.throwBusinessException(ex);
        }
    }

    private void constructionQQMailProperties(Properties p) {
        //setProperty()--调用Hashtab下的put方法

        p.setProperty("mail.pop3.host", "pop.ehuatai.com"); // 按需要更改
        p.setProperty("mail.pop3.port", "995");
        // SSL安全连接参数
        p.setProperty("mail.pop3.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        p.setProperty("mail.pop3.socketFactory.fallback", "true");
        p.setProperty("mail.pop3.socketFactory.port", "995");
    }

    private void loadBillInfo(BillMailInfoDTO dto, Cust cust) throws BusinessException {
        if (StringUtils.isNotBlank(dto.getCustName())
                && !dto.getCustName().equals(cust.getName())) {
            logger.info("非本人信用卡账单，不处理");
            return;
        }
        if(StringUtils.isBlank(dto.getBillDate())){
            logger.info("账单日不能为空");
            return;
        }
        // 处理 卡信息
        if (StringUtils.isNotBlank(dto.getCardCode())) {
            List<Card> cards = cardService.queryCardListByCustId(cust.getId());
            // 后四位进行对比
            String cardCode = dto.getCardCode();
            String code = cardCode.substring(cardCode.length() -4,cardCode.length()) ;
            Card c = null;
            for(Card card:cards){
                String ccardCode = card.getCode() ;
                String ccode = ccardCode.substring(ccardCode.length() -4,ccardCode.length()) ;
                if(ccode.equals(code)) {
                    c = card ;
                    break;
                }
            }
            //如果卡不存在，则先新增卡
            if(c == null) {
                c = new Card() ;
                c.setCustId(cust.getId());
                c.setCardType(Constants.card_type_credit);
                c.setCode(cardCode);
                c.setBankId(dto.getBankId());
                cardService.addCard(c);
            }
            //如果信用卡不存在，则先新增信用卡
            CreditCardInfo creditCardInfo = creditCardInfoService.queryCreditCardInfoByCardId(c.getId()) ;
            if(creditCardInfo == null ) {
                creditCardInfo = new CreditCardInfo();
                creditCardInfo.setCardId(c.getId());
                creditCardInfoService.addCreditCardInfo(creditCardInfo);
            }
            if(StringUtils.isNotBlank(dto.getCardName())) {
                // 卡种信息
                String cardName = dto.getCardName() ;
                CreditCardType cardType = creditCardTypeService
                        .queryCreditCardType(dto.getBankId(),cardName) ;
                if(cardType == null) {
                    cardType = new CreditCardType();
                    cardType.setBankId(dto.getBankId());
                    cardType.setName(cardName);
                    creditCardTypeService.addCreditCardType(cardType);
                }
                creditCardInfo.setCardTypeId(cardType.getId());
            }

            if(dto.getCreditLimit() != null) {
                creditCardInfo.setAmount(dto.getCreditLimit());
            }
            creditCardInfo.setBillEmail(dto.getEmail());
            creditCardInfo.setBillEmailPassword(dto.getPassword());
            if(StringUtils.isBlank(creditCardInfo.getBillDate())
                || Integer.parseInt(creditCardInfo.getBillDate())
                    <= Integer.parseInt(dto.getBillDate())) {
                String nextDate = DateUtils.getNextMonthDate(dto.getBillDate()) ;
                creditCardInfo.setBillDate(nextDate);
            }
            creditCardInfoService.modifyCreditCardInfo(creditCardInfo);
            // 处理账单信息
            if(StringUtils.isNotBlank(dto.getBillMonth())) {
                BillInfo billInfo = billInfoService.queryCreditCardBillInfo(creditCardInfo.getCardId(),dto.getBillDate()) ;
                if(billInfo == null) {
                    billInfo = new BillInfo() ;
                    billInfo.setType("1");
                    billInfo.setBillMonth(dto.getBillMonth());
                    billInfo.setBillDate(dto.getBillDate());
                    billInfo.setDeadlineDate(dto.getDeadlineDate());
                    billInfo.setTotalAmount(dto.getTotalAmount());
                    billInfo.setResidueAmount(dto.getTotalAmount());
                    billInfo.setMinRepayAmount(dto.getMinRepayAmount());
                    billInfo.setIssuerId(creditCardInfo.getCardId());
                    billInfo.setStatus("0");
                    String cCode =  cardCode.length() > 4 ? cardCode.substring(cardCode.length()-4 ):cardCode ;
                    billInfo.setName(Cache.bankCache.get(dto.getBankId()).getName()+" " + cCode);
                    billInfoService.addBillInfo(billInfo);
                }
            }
            // 处理积分信息
            if(dto.getPoint() != null) {
                //TODO 判断是否是最新的账单，最新的账单才更新
            }
            // 处理消费记录信息
            if(ListUtils.isNotEmpty(dto.getTradeRecordDTOS())) {

            }

        }



    }
}
